<?php

namespace App\Admin\Actions\Grid\Withdraw;

use App\Jobs\SendTransaction;
use App\Models\UserWallet;
use App\Models\UserWithdraw;
use App\Services\Base\HelpService;
use App\Services\BlockChainServices;
use Dcat\Admin\Grid\BatchAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class SendTxBatchGrid extends BatchAction
{
    protected $action;

// 注意action的构造方法参数一定要给默认值
    public function __construct($title = null, $action = 1)
    {
        $this->title = $title;
        $this->action = $action;
    }

// 确认弹窗信息
    public function confirm()
    {
        return "您确定要$this->title";
    }


    public function handle(Request $request)
    {
        $keys = $this->getKey();
        // 获取请求参数
        /**
         * @var $user_wallet UserWallet
         */
        $user_wallet = UserWallet::query()->where('status', 1)->first();
        if (!$user_wallet) {
            return $this
                ->response()
                ->error("出款地址不存在")
                ->refresh();
        }
        try {
            DB::beginTransaction();
            /**
             * @var  $user_withdraw UserWithdraw
             */
            foreach (UserWithdraw::find($keys) as $user_withdraw) {
                if ($user_withdraw->tx_status != TX_STATUS_UNTREATED && $user_withdraw->tx_status != TX_STATUS_FAIL) {
                    continue;
                }

                if ($user_withdraw->status != TRADE_STATUS_UNTREATED) {
                    continue;
                }

                if (!$user_withdraw->to_address) {
                    continue;
                }

                BlockChainServices::addressSet("TRON", strtolower($user_withdraw->to_address));
                $user_withdraw->tx_status = TX_STATUS_PROCESSING;
                $user_withdraw->from_address = $user_wallet->address;
                $chain = $user_withdraw->chain;
                $user_withdraw->contract = config("coins.withdraw_contract.$chain");
                $user_withdraw->save();
                SendTransaction::dispatch(1, $user_withdraw)->onQueue("send_transaction");;
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            HelpService::forceLog($e, 'RebateIncomeBatchGrid');
        }


        return $this->response()->success("操作成功")->refresh();
    }

// 设置请求参数
    public function parameters()
    {
        return [
            'action' => $this->action,
        ];
    }

}
